const app = getApp()
const api = app.globalData.target
const Toast = app.globalData.Toast
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phoneNumber:"",
    password:"",
    confirmPwd:"",
  },
  failToast(msg){
    Toast({
      type:"fail",
        message:msg,
        mask:true,
        duration:1500
    })
  },
  /**
   * 检验用户输入有效性
   */
  check(phoneNumber,password,confirmPwd){
    // 手机号正则
    let re1 = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/
    // 密码正则：至少8位，需包含一位数字，一位字母
    let re2 = /^.*(?=.{8,})(?=.*\d)(?=.*[a-zA-Z]).*$/
    if(phoneNumber == null || password == null || confirmPwd == null || !re1.test(phoneNumber)){
      // console.log(phoneNumber==null,password==null,confirmPwd==null,re1.test(phoneNumber))
      this.failToast("输入内容无效")
    }else if(!re2.test(password)){
      this.failToast("密码过于简单")
    }else if(password !== confirmPwd){
      this.failToast("密码不一致")
    }else{
      return true
    }

    return false
  },
  // 注册账号
  register(){
    let {phoneNumber,password,confirmPwd} = this.data
    let isValid = this.check(phoneNumber,password,confirmPwd)
    if(!isValid){
      return
    }

    wx.request({
      url: api+'/register',
      method:"POST",
      data:{
        phoneNumber,
        password
      },
      timeout:3000,     
      success(res){
        // 账号创建成功，自动跳转个人信息完善页面
        console.log(res.data);
        if(res.data.code === 200){
          wx.redirectTo({
            url: '/pages/addUserInfo/index?phoneNumber='+phoneNumber,
          })
        }else{
          Toast({
            type:"fail",
            message:res.data.message
          })
        }
      },
      fail(err){

      }
    })

  }
})